package jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BlobTest {
	public static void main(String[] args) throws Exception {
//		uploadpic();
		downloadpic();
	}

	private static void downloadpic() throws Exception {
		String sql="select * from hh_users where id=22";
		Connection con=null;
		PreparedStatement pst= null;
		ResultSet rs=null;
		try {
			con = DBUtil.open();
			pst=con.prepareStatement(sql);
			rs = pst.executeQuery();
			if(!rs.next())
				return;
			System.out.println(rs.getString("name"));
			InputStream in =rs.getBinaryStream("headpic");
			FileOutputStream out = new FileOutputStream(new File("/home/tarena/Desktop/5.jpg"));
			byte[] buf=new byte[4096];
			int len;
			while((len=in.read(buf))!=-1){
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
		} finally {
			DBUtil.close(con, pst, rs);
		}
	}

	private static void uploadpic() throws Exception{
		Connection con=null;
		PreparedStatement pst= null;
		String sql="insert into hh_users (id,name,headpic) values(hh_stu_seq.nextval,?,?)";
		try {
			con = DBUtil.open();
			pst=con.prepareStatement(sql);
			pst.setString(1, "chounvwudi");
			File file=new File("/home/tarena/Desktop/4.jpg");
			FileInputStream in=new FileInputStream(file);
			pst.setBinaryStream(2, in,(int)file.length());
//			pst.setBlob(2, in);
			pst.executeUpdate();
			in.close();
		} finally {
			DBUtil.close(con, pst, null);
		}
	}
}
